Imports System
Imports System.Collections.Generic
Imports System.Text

Namespace SerialPortService

    Public Class SerialPortService
        Inherits C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery.LocalService
        Private helperThread As System.Threading.Thread
        Private listening As Boolean
        Private sh As C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery.ServiceHandle


        Public Delegate Sub SerialDataEventHandler(ByVal sender As Object, _
                                                    ByVal e As SerialDataEventArgs)
        Public Event NewClientConnected As EventHandler
        Public Event ClientDisconnected As EventHandler
        Public Event DataReceivedFromClient As SerialDataEventHandler
        Public Event DataSentToClient As SerialDataEventHandler

        Public Sub RegisterService()
            sh = Register(C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery. _
                          ServiceType.SerialPortProfile, "SPP Service", _
                          "Serial Port Profile Service")
            listening = True
            helperThread = New System.Threading.Thread(AddressOf ThreadFunction)
            helperThread.Start()
        End Sub

        Public Overloads Overrides Sub UnRegister()
            listening = False
            MyBase.UnRegister()
        End Sub

        Private Sub ThreadFunction()
            While listening

                ' Wait for incoming connections.
                While listening AndAlso Not sh.ConnectionsPending()
                    System.Threading.Thread.Sleep(10)
                End While

                If Not listening Then
                    Exit While
                End If

                ' Accept a waiting connection.
                Dim ns As System.Net.Sockets.NetworkStream = sh.AcceptConnection()
                RaiseEvent NewClientConnected(Me, New EventArgs())

                ' Raise the NewClientConnected event.
                Try
                    Const bufferSize As Integer = 4096

                    While listening
                        Dim buffer() As Byte

                        ' Write to the client.
                        Dim dataSent As String = "Hello from " & Me.Name
                        buffer = Encoding.ASCII.GetBytes(dataSent)
                        ns.Write(buffer, 0, buffer.Length)
                        RaiseEvent DataSentToClient(Me, New SerialDataEventArgs(dataSent))

                        ' Raise the DataSentToClient event.

                        ' Read the client's response.
                        buffer = New Byte(bufferSize - 1) {}
                        Dim length As Integer = ns.Read(buffer, 0, buffer.Length)
                        Dim dataReceived As String = Encoding.ASCII.GetString(buffer, _
                                                                              0, length)

                        ' Raise the DataReceivedFromClient event.
                        RaiseEvent DataReceivedFromClient(Me, New SerialDataEventArgs _
                                                                        (dataReceived))
                    End While

                Catch
                    ns.Close()
                End Try

                RaiseEvent ClientDisconnected(Me, New EventArgs())

                System.Threading.Thread.Sleep(1000)
            End While

        End Sub

    End Class

End Namespace
